package com.example.study.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis-plus 配置
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
//        log.info("start insert fill ....");
//        this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
        this.fillStrategy(
                metaObject, "createTime", getDataString()
        );
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        log.info("start update fill ....");
//        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime",getDataString(), metaObject);
    }

    private String getDataString() {
        Date date = new Date(); // this object contains the current date value

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        log.info("当前时间" + formatter.format(date));
        return formatter.format(date);
    }
}